import { type ProColumns, ProTable, TableDropdown } from '@ant-design/pro-components';
import { Button, Input, Select, Modal, Switch, Tag, message } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { addUser, getUserList, getUserDetail, editUser, deleteUser, updateUserStatus, resetPassword } from 'apis/user';
import dayjs from 'dayjs';
import Add from './Add';
import Edit from './Edit';
import Password from './Password';

export default function ({ parentNode }):JSX.Element {
    const [passwordVisible, setPasswordVisible] = useState(false);

    const [addVisible, setAddVisible] = useState(false);
    const [editVisible, setEditVisible] = useState(false);

    const [userId, setUserId] = useState(false);

    const columns: ProColumns[] = [
        {
            title: '用户名',
            dataIndex: 'userName',
        },
        {
            title: '姓名',
            dataIndex: 'name',
        },
        {
            title: '手机号',
            dataIndex: 'mobile',
            hideInSearch: true,
        },
        {
            title: '状态',
            dataIndex: 'validStat',
            // filters: true,
            // onFilter: true,
            valueType: 'select',
            valueEnum: {
                1: { text: '启用' },
                0: { text: '停用' },
            },

            render: (_, record) => (
                <Switch
                    checkedChildren='启用'
                    unCheckedChildren='停用'
                    checked={record.validStat === 1}
                    onClick={() => onDisEnableStatus(record)}
                />
            ),
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            hideInSearch: true,
            renderText(text) {
                return dayjs(Number(text)).format('YYYY-MM-DD HH:mm:ss');
            },
        },
        {
            title: '操作',
            width: 180,
            key: 'option',
            valueType: 'option',
            render: (_, record) => [
                <Button
                    onClick={() => {
                        setUserId(record.id);
                        setEditVisible(true);
                    }}
                    key='link'
                >
                    修改
                </Button>,
                <Button
                    onClick={() => {
                        setUserId(record.id);
                        setPasswordVisible(true);
                    }}
                    key='link2'
                >
                    重置密码
                </Button>,
                <Button onClick={() => handleDel(record.id)} key='link3'>
                    删除
                </Button>,
            ],
        },
    ];

    // 表格操作
    const tableRef = useRef();
    const refresh = () => {
        tableRef.current?.reload();
    };
    const commonAction: ({
        title,
        content,
        api,
    }: {
        title: string;
        content: string;
        api: () => Promise<any>;
        successMsg: string;
    }) => void = ({ title, content, api, successMsg }) => {
        Modal.confirm({
            title,
            content,
            okText: '确定',
            cancelText: '取消',
            centered: true,
            async onOk() {
                return new Promise<void>(async (resolve, reject) => {
                    try {
                        await api();
                        message.success(successMsg);
                        resolve();
                        refresh();
                    } catch (error) {
                        reject();
                    }
                });
            },
        });
    };

    const onDisEnableStatus = (record) => {
        commonAction({
            title: '提示',
            content: `确定要${record.validStat === 1 ? '停用' : '启用'}吗`,
            api: () => updateUserStatus({
                id: record.id,
                validStat: record.validStat === 1 ? 0 : 1,
            }),
            successMsg: `用户${record.validStat === 1 ? '已停用' : '已启用'}`,
        });
    };

    const handleDel = (id?: string) => {
        commonAction({
            title: '提示',
            content: '确定删除此用户',
            api: () => deleteUser({
                id,
            }),
            successMsg: '用户删除成功',
        });
    };

    return (
        <>
            <Add visible={addVisible} setVisible={setAddVisible} refresh={refresh} organization={parentNode} />
            <Edit
                visible={editVisible}
                setVisible={setEditVisible}
                refresh={refresh}
                userId={userId}
                organization={parentNode}
            />
            <Password visible={passwordVisible} setVisible={setPasswordVisible} userId={userId} />
            <ProTable
                params={{
                    organizationId: parentNode?.id,
                }}
                actionRef={tableRef}
                columns={columns}
                request={async (params) => {
                    // 表单搜索项会从 params 传入，传递给后端接口。
                    console.log(params);
                    const res = await getUserList({ ...params, ...{ pageNumber: params.current, current: undefined } });
                    console.log(res);
                    return Promise.resolve({
                        total: res?.totalRow,
                        data: res.recordDatas || [],
                        organizationId: params.organizationId,
                        success: true,
                    });
                }}
                rowKey='id'
                pagination={{
                    showQuickJumper: true,
                }}
                search={{
                    layout: 'vertical',
                    defaultCollapsed: false,
                }}
                dateFormatter='string'
                toolBarRender={() => [
                    <Button type='primary' key='primary' onClick={() => setAddVisible(true)}>
                        新建
                    </Button>,
                ]}
                scroll={{
                    y: '66vh',
                }}
            />
        </>
    );
}
